package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.CateNavigationModel;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.skeleton.ViewSkeletonScreen;
import com.zahb.qadx.ui.adapter.NewsFragmentAdapter;
import com.zahb.qadx.ui.fragment.NewsAllFragment;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by： huwei.
 * Data： 2020-10-22.
 * Time： 15:10.
 * Desc：新闻列表
 */
public class NewsListActivity extends BaseActivity {
    @BindView(R.id.tab_news)
    TabLayout tabNews;
    @BindView(R.id.img)
    AppCompatImageView img;
    @BindView(R.id.vp_new)
    ViewPager2 vpNew;
    private List<CateNavigationModel.NavigationData> new_tab_list = new ArrayList<>();
    private List<Fragment> new_vp_list;
    private List<String> listTitle = new ArrayList<>();

    private ViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LiveEventBus.get("hideSkeleton", String.class)
                .observe(this, s -> {
                    if (TextUtils.equals("hideSkeleton", s)) {
                        hideSkeleton();
                    }
                });
        showSkeleton();
    }

    private void showSkeleton() {
        mSkeletonScreen = Skeleton.bind(img)
                .shimmer(false)
                .angle(15)
                //.color(R.color.light_transparent)
                .duration(1000)
                .load(R.layout.skeleton_image)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_news;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        getCoverPath();
        getCateList();
        new_tab_list = new ArrayList<>();
        new_vp_list = new ArrayList<>();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.news_list;
    }

    private void getCoverPath() {
//        String json = "{\"pageNo\":1,\"pageSize\":1,\"isPublish\":1,\"isTop\":1}";
//        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
//        addDisposable(RetrofitService.getNetService().getNewsListData(body)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(response -> {
//                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
//                        ImageLoader.loadImage(img, response.getData().getList().get(0).getCoverPath());
//                    }
//                }, Throwable::printStackTrace));
          //新改推荐类接口
        addDisposable(RetrofitService.getNetService()
                .getRecommendedNews(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        ImageLoaderKt.loadImage(img, response.getData().get(0).getCoverPath());
                    }
                }, Throwable::printStackTrace));


    }

    /**
     * 获取新闻分类列表
     */
    private void getCateList() {
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            showProgressDialog("数据加载中...");
            addDisposable(RetrofitService.getNetService()
                    .getListData()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getStatusCode() == 200) {
                            getNavigationListData(response);
                        } else {
                            hideProgressDialog();
                        }
                    }, throwable -> {
                        hideProgressDialog();
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                    }));
        }
    }

    private void getNavigationListData(CommonResponse<List<CateNavigationModel.NavigationData>> response) {
        listTitle.clear();
        //全部
        NewsAllFragment fragmentAll = new NewsAllFragment();
        Bundle bundleAll = new Bundle();
        bundleAll.putInt("id", -1);
        bundleAll.putString("name", "全部");
        fragmentAll.setArguments(bundleAll);
        new_vp_list.add(0, fragmentAll);
        listTitle.add("全部");
        new_tab_list.addAll(response.getData());
        int index = -1;
        int sourceId = getIntent().getIntExtra("sourceId", -1);
        if (response.getStatusCode() == 200) {
            for (int i = 0; i < new_tab_list.size(); i++) {
                CateNavigationModel.NavigationData item = new_tab_list.get(i);
                NewsAllFragment fragment = new NewsAllFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("id", item.getCateId());
                bundle.putString("name", item.getCateName());
                bundle.putParcelableArrayList("child", new ArrayList<>(item.getChildren()));
                fragment.setArguments(bundle);
                new_vp_list.add(fragment);
                listTitle.add(item.getCateName());
                if (sourceId == item.getCateId()) {
                    index = i;
                }
            }
            vpNew.setAdapter(new NewsFragmentAdapter(this, new_vp_list));
            vpNew.setOffscreenPageLimit(new_vp_list.size() - 1);
            TabLayoutMediator mediator = new TabLayoutMediator(tabNews, vpNew,
                    (tab, position) -> tab.setText(listTitle.get(position)));
            mediator.attach();
            if (index != -1)
                vpNew.setCurrentItem(index + 1, false);
        }
    }

    public static void actionStart(Context context, int sourceId) {
        Intent intent = new Intent(context, NewsListActivity.class);
        intent.putExtra("sourceId", sourceId);
        context.startActivity(intent);
    }
}
